<template>
    <div class="container mCom" id="mCom" style="background:#fff">
       <div class="search-box">
        <div class="btn">
            <el-button size="medium" type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">新增</el-button>
            <el-button size="medium" type="primary" icon="el-icon-delete" @click="handleDelete">删除</el-button>
        </div>
        <div class="search">
            <el-input size="medium" clearable v-model="pagination.name" @keyup.enter.native="handleSearch" style="width: 240px; margin-right: 10px" placeholder="请输入数据库名称"></el-input>
            <el-button size="medium" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
       </div>
        <el-table
      v-loading="loading"
      :data="DataList"
      :header-cell-style="{background:'#F5F5F5'}"
      border
      @selection-change="handleSelectionChange"
      :row-key="getRowKeys"
    >
      <!-- <el-table-column label="选择"   type="selection"
      width="55">
        <template slot-scope="{ row }">
          <el-radio :label="row.id"  v-model="RowId" @change="cardRadionChange(row)"><span></span></el-radio>
        </template>
      </el-table-column> -->
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>

      <el-table-column label="序号" align="center" type="index" width="60"/>
      <el-table-column label="数据源名称" align="center" prop="dataSourceName" />
      <el-table-column
        label="数据库名称"
        align="center"
        prop="dbName"
      />
      <el-table-column
        label="数据源类型"
        align="center"
        prop="dbType"
      />
      <el-table-column
        label="IP地址"
        align="center"
        prop="dbHost"
      />
      <el-table-column
        label="端口号"
        align="center"
        prop="port"
      />
      <el-table-column
        label="用户名"
        align="center"
        prop="userName"
      />
      <!-- <el-table-column
        label="密码"
        align="center"
        prop="password"
      /> -->
      <el-table-column
        label="链接URL"
        align="center"
        prop="dbUrl"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-copy-document"
            @click="handleDetail(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagesize">
      <div id="fy" class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.pageNumber" :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next"
        :total="total"></el-pagination>
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="数据源名称" prop="dataSourceName">
          <el-input
            maxlength="20"
            v-model="form.dataSourceName"
            placeholder="请输入数据源名称"
          />
        </el-form-item>
        <el-form-item label="数据源类型" prop="dbType">
          <el-select v-model="form.dbType" placeholder="请选择数据源类型" @change='handleChange($event)'>
            <el-option v-for="item in dataType" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="ip地址" prop="dbHost">
          <el-input
            maxlength="20"
            v-model="form.dbHost"
            placeholder="请输入ip地址"
          />
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input
            maxlength="20"
            v-model="form.port"
            placeholder="请输入端口号"
          />
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbName">
          <el-input
            maxlength="20"
            v-model="form.dbName"
            placeholder="请输入数据库名称"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            maxlength="20"
            v-model="form.userName"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            maxlength="20"
            :type="passw"
            v-model="form.password"
            placeholder="请输入密码"
          >
            <i slot="suffix" :class="icon" @click="showPass"></i></el-input>
        </el-form-item>
        <el-form-item label="链接URL" prop="dbUrl">
          <el-input
            v-model="form.dbUrl"
            placeholder="请输入链接URL"
          />
        </el-form-item>
        <el-form-item label="连接属性" prop="connectAttribute">
          <el-input
            type="textarea"
            maxlength="200"
            :rows="2"
            v-model="form.connectAttribute"
            placeholder="请输入连接属性"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="medium" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="medium" type="success" @click="handleSubmitTest">测试连接</el-button>
        <el-button size="medium" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    </div>
</template>
<script>
import { delDataSource } from "../../api/sourceDetail";
export default {
  name: "",
  data() {
    return {
      delIDList: [],
      icon: "el-input__icon el-icon-view",
      passw: "password",
      connectionSuccessful: false,
      // 数据
      DataList: [],
      loading: false,
      pagination: {
        pageSize: 10,
        pageNumber: 1,
        name: ""
      },
      total: 0,
      // 弹框标题
      title: "新增",
      // 弹框显示隐藏
      open: false,
      //类型数据
      dataType: [
        {
          name: "mysql",
          id: "mysql",
          value: "jdbc:mysql://<machine_name>:<port>/<dbname>"
        },
        {
          name: "oracle",
          id: "oracle",
          value: "jdbc:oracle:thin:@<machine_name>:<port>:<dbname>"
        },
        {
          name: "postgresql",
          id: "postgresql",
          value: "jdbc:postgresql://<machine_name>:<port>/<dbname>"
        },
        {
          name: "达梦8",
          id: "dm",
          value: "jdbc:dm://<machine_name>:<port>/<dbname>"
        }
      ],
      form: {
        db_url: "",
        data_source_name: "",
        db_type: "",
        programmeName: "",
        port: "",
        db_name: "",
        user_name: "",
        password: ""
      },
      // 表单规则
      rules: {
        dataSourceName: [
          { required: true, message: "请填写数据源名称", trigger: "blur" },
          { min: 1, max: 99, message: "长度在 1 到 99 个字符", trigger: "blur" }
        ],
        dbHost: [{ required: true, message: "请填写ip地址", trigger: "blur" }],
        dbUrl: [
          { required: true, message: "请填写数据库连接url", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "请填写数据库连接用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请填写数据库连接密码", trigger: "blur" }
        ],
        port: [{ required: true, message: "请填写端口号", trigger: "blur" }],
        dbType: [
          { required: true, message: "请选择数据源类型", trigger: "change" }
        ],
        dbName: [
          { required: true, message: "请填写数据库名称", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    filterPreviewType() {
      var type = this.databaseType.filter(
        node => node.value == this.dbMsg.dataType
      )[0];
      if (type.label == "HIVE") {
        return this.previewType.filter(node => node.value == "ONLY100");
      } else {
        return this.previewType;
      }
    },
    databaseUpload: function() {
      return this.$store.state.datasource.databaseUpload;
    },
    dbMsg: function() {
      //数据表链接信息
      return this.databaseUpload.dbMsg;
    },
    dataColumnName: function() {
      //数据列头
      return this.databaseUpload.dataColumnName;
    },
    dataListTitle: function() {
      //数据列头
      return this.databaseUpload.dataListTitle;
    },
    // dataList: function() {
    //   //预览数据
    //   var oldData = this.databaseUpload.dataList;
    //   var result = [];
    //   var tempTitles = [];
    //   try {
    //     if (oldData.length > 0) {
    //       tempTitles = Object.keys(oldData[0]);
    //     }
    //     oldData.forEach(function(item) {
    //       var tempItem = {};
    //       tempTitles.forEach(function(key) {
    //         if (key.indexOf(".") == -1) {
    //           tempItem[key] = item[key];
    //         } else {
    //           var temp = key.split(".");
    //           tempItem[temp[1]] = item[key];
    //         }
    //       });
    //       result.push(tempItem);
    //     });
    //   } catch (e) {
    //     console.error(e.message);
    //   }
    //   return result;
    // },
    statue: function() {
      //dialog弹出状态
      return this.$store.state.datasource.deals.statue;
    },
    regexp: function() {
      return this.$store.state.global.regexp;
    }
  },
  created() {
    this.GETList();
  },
  methods: {
    showPass() {
      //点击图标是密码隐藏或显示
      if (this.passw == "text") {
        this.passw = "password";
        //更换图标
        this.icon = "el-input__icon el-icon-view";
      } else {
        this.passw = "text";
        this.icon = "iconfont icon-biyan";
      }
    },
    handleChange(e) {
      this.dataType.filter(item => {
        if (item.id == e) {
          this.form.dbUrl = item.value;
        }
      });
    },
    // 详情
    handleDetail(row) {
      this.$router.push({
        name: "datasourceDetail",
        query: {
          id: row.id,
          type: row.dbType
        }
      });
    },
    // 删除按钮
    handleDelete() {
      if (this.delIDList.length < 1) {
        this.$message.error("请选择你要删除的数据！");
        return;
      }
      this.$confirm("此操作将删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delDataSource(this.delIDList).then(res => {
            if (res.status == "SUCCESS") {
              this.$message.success(res.message);
              this.GETList();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {});
    },
    // 搜索
    handleSearch() {
      this.GETList();
    },
    // 获取数据源数据
    GETList() {
      let that = this;
      this.$.ajax({
        url:
          that.$store.state.global.httpServer +
          "/api/datasource/getDataSourceListByPage/" +
          that.pagination.pageNumber +
          "/" +
          that.pagination.pageSize +
          "/" +
          that.pagination.name,
        method: "get",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: function(xhr) {
          this.loading = true;
          xhr.setRequestHeader("accessToken", localStorage.accessToken);
        },
        success: function(data) {
          if (data.status == "SUCCESS") {
            // that.$notify({
            //   title: "成功",
            //   message: data.message,
            //   type: "success"
            // });
            that.DataList = data.data.content;
            that.total = data.data.totalElements;
            this.loading = false;
          } else if (data.status == "FAIL") {
            that.$notify.error({
              title: "失败",
              message: data.message
            });
          }
        },
        error: function(response) {
          that.$store.commit("dealRequestError", response);
        }
      });
    },
    // 编辑
    handleUpdate(row) {
      let that = this;
      that.open = true;
      that.title = "编辑";
      this.$.ajax({
        url:
          that.$store.state.global.httpServer +
          "/api/datasource/getDataSourceById/" +
          row.id,
        method: "get",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: function(xhr) {
          that.loading = true;
          xhr.setRequestHeader("accessToken", localStorage.accessToken);
        },
        success: function(data) {
          if (data.status == "SUCCESS") {
            // that.$notify({
            //   title: "成功",
            //   message: data.message,
            //   type: "success"
            // });
            that.form = JSON.parse(JSON.stringify(data.data));
            that.loading = false;
          } else if (data.status == "FAIL") {
            that.$notify.error({
              title: "失败",
              message: data.message
            });
          }
        },
        error: function(response) {
          that.$store.commit("dealRequestError", response);
        }
      });
    },
    // 添加提交按钮
    submitForm() {
      this.$refs["form"].validate(valid => {
        let that = this;
        if (valid) {
          if (that.form.id) {
            this.$.ajax({
              url:
                that.$store.state.global.httpServer +
                "/api/datasource/updateDataSource",
              method: "put",
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              data: JSON.stringify(that.form),
              beforeSend: function(xhr) {
                xhr.setRequestHeader("accessToken", localStorage.accessToken);
              },
              success: function(data) {
                if (data.status == "SUCCESS") {
                  that.$notify({
                    title: "成功",
                    message: data.message,
                    type: "success"
                  });
                  //完成创建，取消弹出框，刷新列表
                  that.open = false; //隐藏弹出框
                  that.GETList();
                  // that.$store.dispatch("getMenuDatabaseList");
                  that.reForm();
                  that.$refs.form.resetFields();
                } else if (data.status == "FAIL") {
                  that.$notify.error({
                    title: "失败",
                    message: data.message
                  });
                }
              },
              error: function(response) {
                that.$store.commit("dealRequestError", response);
              }
            });
          } else {
            if (this.connectionSuccessful) {
              this.$.ajax({
                url:
                  that.$store.state.global.httpServer +
                  "/api/datasource/insertDataSource",
                method: "post",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify(that.form),
                beforeSend: function(xhr) {
                  xhr.setRequestHeader("accessToken", localStorage.accessToken);
                },
                success: function(data) {
                  if (data.status == "SUCCESS") {
                    that.$notify({
                      title: "成功",
                      message: data.message,
                      type: "success"
                    });
                    that.$refs.form.resetFields();
                    //完成创建，取消弹出框，刷新列表
                    that.open = false; //隐藏弹出框
                    that.GETList();
                    // that.$store.dispatch("getMenuDatabaseList");
                    that.reForm();
                  } else if (data.status == "FAIL") {
                    that.$notify.error({
                      title: "失败",
                      message: data.message
                    });
                  }
                },
                error: function(response) {
                  that.$store.commit("dealRequestError", response);
                }
              });
            } else {
              that.$message.error("请先测试连接");
            }
          }
        } else {
          that.$message.error("表单填写错误请检查！");
          return;
        }
      });
    },
    // 测试链接
    handleSubmitTest() {
      let that = this;
      const data = {
        userName: this.form.userName,
        password: this.form.password,
        url: this.form.dbUrl
      };
      this.$.ajax({
        url:
          that.$store.state.global.httpServer +
          "/api/datasource/connectTestByDataType",
        method: "post",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        beforeSend: function(xhr) {
          xhr.setRequestHeader("accessToken", localStorage.accessToken);
        },
        success: function(data) {
          if (data.status == "SUCCESS") {
            that.$notify({
              title: "成功",
              message: data.message,
              type: "success"
            });
            this.connectionSuccessful = true;
            //完成创建，取消弹出框，刷新列表
            // that.$store.dispatch("getMenuDatabaseList");
          } else if (data.status == "FAIL") {
            that.$notify.error({
              title: "失败",
              message: data.message
            });
            this.connectionSuccessful = false;
          }
        },
        error: function(response) {
          that.$store.commit("dealRequestError", response);
        }
      });
    },
    // 批量选择
    handleSelectionChange(val) {
      this.delIDList = val.map(item => {
        return item.id;
      });
    },
    getRowKeys(row) {
      //记录每行的key值
      return row.id;
    },
    // 分页
    handleSizeChange(val) {
      //选择不同页数时触发事件
      this.pagination.pageSize = val; //修改每页条数
      this.GETList();
    },
    handleCurrentChange(val) {
      //当前页变化时触发事件
      this.pagination.pageNumber = val; //修改当前页
      this.GETList();
    },
    // 清除表单
    reForm() {
      this.connectionSuccessful = false;
      this.form = {
        db_url: "jdbc:mysql://<machine_name>:<port>/<dbname>",
        data_source_name: "",
        db_type: "",
        programmeName: "",
        port: "",
        db_name: "",
        user_name: "",
        password: ""
      };
    },
    // 新增
    handleAdd() {
      this.reForm();
      this.open = true;
      this.icon = "el-input__icon el-icon-view";
    },
    // 取消
    cancel() {
      this.reForm();
      this.open = false;
      this.$refs.form.resetFields();
    }
  }
};
</script>
<style scoped>
.container .search-box {
  width: calc(100% - 140px);
  height: 30px;
  line-height: 30px;
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
}
.iconfont {
  font-size: 25px;
}
</style>
